package com.szewec.ps.ui.road.facilities.investigation.task;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivityRoadBridgeBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.road.facilities.investigation.task.RoadBridge;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTask;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTaskDTO;
import com.szewec.ps.model.selectmappoint.SelectedPoint;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;

import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class RoadBridgeActivity extends BaseMediaPickerActivity {
    private ActivityRoadBridgeBinding binding;

    /********字典start***********/
    // 布置形式
    private ArrayList<String> layoutFormDict = new ArrayList<>();
    /********字典end***********/
    private String modeFlag; // 用于区分新增还是修改还是详情展示
    private ViewModeValue viewModeValue;
    // 坐标相关
    private final static int START_POINT_CODE = 1;
    private final static int END_POINT_CODE = 2;
    private SelectedPoint centerPoint;
    private String startPointStr;
    private String endPointStr;
    // 桥梁对象
    private RoadBridge roadBridge = new RoadBridge();
    // 路段设施调查任务DTO
    private RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO roadFacilitiesTaskDTO;

    // 照片上传数组
    private List<String> photoSketchUploadIdArr = new ArrayList<>();
    // 照片文件数组
    private ArrayList<MediaFile> photoSketchFileArr = new ArrayList<>();
    // 图片适配器
    private CustomPickerAdapterShowAndEdit photoSketchAdapter;
    // 移除的图片ID数组
    private List<String> deletePhotoIdArr = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_road_bridge);
        ButterKnife.bind(this);
        initData();
        initView();
        initTitleBar();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 初始化字典
        layoutFormDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.layoutForm)));
        // 获取intent中的数据
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue =
                (PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO>) getIntent().getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        roadFacilitiesTaskDTO = presentValue.getT();
        Log.i("桥梁getData", JSONObject.toJSONString(roadFacilitiesTaskDTO));
    }

    /**
     * 初始化界面样式
     */
    private void initView() {
        viewModeValue = new ViewModeValue(this, modeFlag, binding.titleBar, binding.llContainer);

        // 初始化照片适配器
        photoSketchAdapter = initTypeMediaRecyclerView(photoSketchUploadIdArr, photoSketchFileArr,
                binding.photoSketchSketchRV, true, false, true, deletePhotoIdArr);

        roadBridge = roadFacilitiesTaskDTO.getRoadBridge() == null ? new RoadBridge() : roadFacilitiesTaskDTO.getRoadBridge();
        // 初始化坐标对象
        SelectedPoint startSelectPoint = JSONObject.parseObject(roadBridge.getStartingPoint(), SelectedPoint.class);
        SelectedPoint endSelectPoint = JSONObject.parseObject(roadBridge.getEndPoint(), SelectedPoint.class);
        startSelectPoint = startSelectPoint == null ? new SelectedPoint() : startSelectPoint;
        endSelectPoint = endSelectPoint == null ? new SelectedPoint() : endSelectPoint;

        binding.bridgeName.setValue(roadBridge.getBridgeName());
        binding.layoutForm.setValue(Enums.BridgeLayoutFormEnum.getValueByKey(roadBridge.getLayoutForm()));
        binding.startingPoint.setValue(startSelectPoint.getxCoordinate(), startSelectPoint.getyCoordinate());
        binding.endPoint.setValue(endSelectPoint.getxCoordinate(), endSelectPoint.getyCoordinate());
        binding.pavementWidth.setValue(roadBridge.getPavementWidth());
        binding.lateralWidth.setValue(roadBridge.getLateralWidth());
        // 设置requestCode 用于区分当前点击的坐标是起点还是终点
        binding.startingPoint.setRequestCode(START_POINT_CODE);
        binding.endPoint.setRequestCode(END_POINT_CODE);
        // 显示附件内容
        initViewFile();
    }

    // 设置照片
    private void initViewFile() {
        // 先根据fileId查询附件数据
        if (!CollectionUtils.isEmpty(roadBridge.getAddIds())) {
            requestFilesByIds(roadBridge.getAddIds(), this::initAdapterData);
        }
        // 根据业务ID查询附件信息
        else if (StringUtils.isNotEmpty(roadBridge.getId())) {
            requestFiles(FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_BRIDGE_FILE_BIZ_TYPE, roadBridge.getId(), this::initAdapterData);
        }
    }

    // 往照片适配器里面设置图片显示
    private void initAdapterData(List<MediaFile> mediaFileList) {
        if (CollectionUtils.isEmpty(mediaFileList)) {
            return;
        }
        photoSketchUploadIdArr.clear();
        photoSketchFileArr.clear();
        // 添加到文件数组
        photoSketchFileArr.addAll(mediaFileList);
        for (MediaFile mediaFile : photoSketchFileArr) {
            photoSketchUploadIdArr.add(mediaFile.getId());
        }
        // 设置适配器数据源
        photoSketchAdapter.setmMediaFileList(mediaFileList);
    }

    private void initTitleBar() {
        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(modeFlag)
                || Constants.PRESENT_VALUE_FLAG.EDIT.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::appendOrModifyData);
        }
    }

    private void appendOrModifyData() {
        // 添加路段调查任务ID
        RoadFacilitiesInvestigationTask facilitiesInvestigationTask = roadFacilitiesTaskDTO.getFacilitiesInvestigationTask();
        if (facilitiesInvestigationTask != null && StringUtils.isNotEmpty(facilitiesInvestigationTask.getId())) {
            roadBridge.setRoadInvestigationTaskId(facilitiesInvestigationTask.getId());
        }
        roadBridge.setBridgeName(binding.bridgeName.getStringValue());
        roadBridge.setLayoutForm(Enums.BridgeLayoutFormEnum.getKeyByValue(binding.layoutForm.getStringValue()));
        roadBridge.setStartingPoint(startPointStr);
        roadBridge.setEndPoint(endPointStr);
        roadBridge.setPavementWidth(binding.pavementWidth.getBigDecimalValue());
        roadBridge.setLateralWidth(binding.lateralWidth.getBigDecimalValue());
        roadBridge.setAddIds(photoSketchUploadIdArr);
        roadBridge.setRemoveIds(deletePhotoIdArr);
        roadFacilitiesTaskDTO.setRoadBridge(roadBridge);
        Log.i("桥梁app", JSONObject.toJSONString(roadFacilitiesTaskDTO));
        Intent intent = new Intent();
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(modeFlag, roadFacilitiesTaskDTO);
        intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
        setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
        finish();
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void deleteData() {

    }

    private void linkToEditActivity() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_BRIDGE_FILE_BIZ_TYPE);
            }
        }

        //选择了坐标
        if (resultCode == Constants.RESULT_CODE.SELECTED_POINT && data != null) {
            Bundle presentValue = data.getExtras();
            centerPoint = (SelectedPoint) presentValue.getSerializable(Constants.EXTRA_KEY.MAP_CENTER_POINT);
            if (centerPoint == null) {
                return;
            }
            switch (requestCode) {
                case START_POINT_CODE:
                    startPointStr = JSONObject.toJSONString(centerPoint);
                    break;
                case END_POINT_CODE:
                    endPointStr = JSONObject.toJSONString(centerPoint);
                    break;
            }
        }
    }

    @OnClick({R.id.layoutForm})
    public void onViewClicked(View view) {
        //隐藏系统软键盘
        TextViewUtil.closeKeyboard(this);
        RollUtil.alertBottomWheelOption(this, layoutFormDict, binding.layoutForm.getSelectTextView(), new RollUtil.OnWheelViewClick() {
            @Override
            public void onClick(View view, int index) {
                binding.layoutForm.setValue(layoutFormDict.get(index));
            }
        });
    }
}